<?php
require_once(ABSPATH . "modules/student.inc.php");
require_once(ABSPATH . "modules/myclass.inc.php");

define("MAX_PERSON_EVERY_PROJECT", 6);
define("MAX_PROJECTS_EVERY_PERSON", 2);
define("MAX_TRACK_ROAD", 6);
define("MAX_TRACK_TEAM", 3);
define("MAX_FIELD_ROAD", 18);
define("MAX_FIELD_TEAM", 1);
/**
 * showSportApplyGridRow()
 *
 * @param array $aApply
 * @param string $sStyle
 * @return
 */
function showSportApplyGridRow($theStudentApply = array())
{
    //var_dump($theStudentApply);
    static $order = 1;
    $sport_apply_id = $theStudentApply['sport_apply_id'];
    $student_no = $theStudentApply['student_no'];
    $student_name = $theStudentApply['student_name'];
    $sex_id = $theStudentApply['sex_id'];

    $form = new zeus_quickform(
        array("name" => "sv-form",
            "id" => "sv-form",
            "action" => "javascript:void(null);",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    // Get sex
    $firstentry = _e('Please Select ...');
    $options = array("1" => _e('Male'),
        "2" => _e('Female')
        );
    // $options[0] = $firstentry;
    $sex = array("property" => array("name" => "sex_id[]"),
        "options" => $options,
        "current" => $sex_id);
    $row[] = "<td class='num'>" . $order++
     . $form->addElement("hidden", array("name" => "sport_apply_id[]", "id" => "sport_apply_id", "value" => $sport_apply_id))
     . "</td>";
    $row[] = "<td><strong>" . $student_name . "</strong></td>";
    $row[] = "<td><strong>" . $sex['options'][$sex_id]. "</strong></td>"; 
    //$row[] = "<td>" . $form->addSelect($sex['property'], $sex['options'], $sex['current']) . "</td>";
    // Get checked status form database
    $checked = getApplyProjectsChecked($sport_apply_id);
    //var_dump($checked);
    $row[] = ($checked[0])?
    ("<td>" . $form->addElement("checkbox", array("name" => "100m[]", "id" => "100m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "100m[]", "id" => "100m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[1])?
    ("<td>" . $form->addElement("checkbox", array("name" => "200m[]", "id" => "200m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "200m[]", "id" => "200m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[2])?
    ("<td>" . $form->addElement("checkbox", array("name" => "400m[]", "id" => "400m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "400m[]", "id" => "400m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[3])?
    ("<td>" . $form->addElement("checkbox", array("name" => "800m[]", "id" => "800m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "800m[]", "id" => "800m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[4])?
    ("<td>" . $form->addElement("checkbox", array("name" => "1000m[]", "id" => "1000m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "1000m[]", "id" => "1000m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[5])?
    ("<td>" . $form->addElement("checkbox", array("name" => "1500m[]", "id" => "1500m", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "1500m[]", "id" => "1500m", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[6])?
    ("<td>" . $form->addElement("checkbox", array("name" => "high_jump[]", "id" => "high_jump", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "high_jump[]", "id" => "high_jump", "value" => $sport_apply_id)) . "</td>");
    $row[] = ($checked[7])?
    ("<td>" . $form->addElement("checkbox", array("name" => "long_jump[]", "id" => "long_jump", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "long_jump[]", "id" => "long_jump", "value" => $sport_apply_id)) . "</td>") ;
    $row[] = ($checked[8])?
    ("<td>" . $form->addElement("checkbox", array("name" => "thows[]", "id" => "thows", "value" => $sport_apply_id, "checked" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "thows[]", "id" => "thows", "value" => $sport_apply_id)) . "</td>");
    /*
    $row[] = ($checked[9])?
    ("<td>" . $form->addElement("checkbox", array("name" => "shot[]", "id" => "shot", "value" => $sport_apply_id, "checked" => true, "disabled" => true)) . "</td>")
    :("<td>" . $form->addElement("checkbox", array("name" => "shot[]", "id" => "shot", "value" => $sport_apply_id, "disabled" => true)) . "</td>");
    */
    $row[] = "</tr>";
    $checked = array();
    return implode("\n\t", $row);
}

/**
 * addNewSport()
 *
 * @param string $sSportName
 * @return
 */
function addNewSport($sSportName = "")
{
    // Add sport name
    $sql = "REPLACE INTO " . DB_PREFIX . "sport SET sport_name='" . $sSportName . "'";
    zeus_sql_exec($sql, false);
    // Get sport id
    $sql = "SELECT sport_id FROM " . DB_PREFIX . "sport WHERE sport_name='" . $sSportName . "'";
    $result = zeus_sql_query($sql, false);
    if (null != $result) {
        $sport_id = $result['sport_id'];
    } else {
        return false;
    }
    // Select current students
    $sql = "SELECT student_no,sex_id FROM " . DB_PREFIX . "rel_student_info WHERE is_enable=1";
    $result = zeus_sql_query($sql, false, 'All');
    if (null != $result) {
        foreach($result AS $student)
        $aStudentNo[] = array(":student_no" => $student['student_no'],
            ":sex_id" => $student['sex_id'],
            ":sport_id" => $sport_id);
    } else {
        return false;
    }
    // var_dump($aStudentNo);
    // Add current student to sport apply list
    if (null != $aStudentNo) {
        $sql = "REPLACE INTO " . DB_PREFIX . "sport_apply SET student_no=:student_no,sport_id=:sport_id,sex_id=:sex_id";
        zeus_sql_prepare($sql, false, $aStudentNo);
        return true;
    } else {
        return false;
    }
}
/**
 * showSportOperation()
 *
 * @return
 */
function showSportOperation()
{
    switch ($_GET['action']) {
        case 'new_sport':
            require_once(ABSPATH . "modules/mgr_sport.inc.php");
            break;
        case 'new_project':
            require_once(ABSPATH . "modules/mgr_project.inc.php");
            break;
        case 'new_group':
            require_once(ABSPATH . "modules/mgr_group.inc.php");
            break;
        case 'sync_list':
            require_once(ABSPATH . "modules/sync_list.inc.php");
            break;
        case 'fresh_apply':
            require_once(ABSPATH . "modules/fresh_apply.inc.php");
            break;
        case 'group_track':
            require_once(ABSPATH . "modules/group_track.inc.php");
            break;
        case 'group_field':
            require_once(ABSPATH . "modules/group_field.inc.php");
            break;
        default: ;
            break;
    } // switch
}

/**
 * showSportApplyForm()
 *
 * @param string $sClassId
 * @return
 */
function showSportApplyForm($sClassId = "")
{
    $form = new zeus_quickform(
        array("name" => "sv-form",
            "id" => "sv-form",
            "action" => "javascript:void(null);",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    $grid = new zeus_datagrid();
    $grid->aColumn = array("order" => array("name" => _e("Order"), "field" => "#"),
        "student_name" => array("name" => _e("Student Name"), "field" => "#"),
        "sex_id" => array("name" => _e("Sex"), "field" => "#"),
        "100m" => array("name" => _e("100 Meters"), "field" => "") ,
        "200m" => array("name" => _e("200 Meters"), "field" => ""),
        "400m" => array("name" => _e("400 Meters"), "field" => ""),
        "800m" => array("name" => _e("800 Meters"), "field" => ""),
        "1000m" => array("name" => _e("1000 Meters"), "field" => ""),
        "1500m" => array("name" => _e("1500 Meters"), "field" => ""),
        "high_jump" => array("name" => _e("High Jump"), "field" => ""),
        "long_jump" => array("name" => _e("Long Jump"), "field" => ""),
        "thows" => array("name" => _e("Thows"), "field" => ""),
        //"shot" => array("name" => _e("Shot"), "field" => ""),
        );
    $aStudentNo = getTheClassStudentNo($sClassId);
    //var_dump($aStudentNo);
    $html[] = "<table class='form-table'>";
    $html[] = "<tr class='form-field'>";
    $html[] = "<th scope='row'>";
    $html[] = "<label for='myclass_id'>";
    $html[] = _e('<strong>STEP 2:</strong>  Chose the apply projects.');
    $html[] = "</label></th><td>";
    $html[] = "<tf class='submit'>";
    $html[] = $form->addElement("submit", array("name" => "step2", "id" => "step2", "value" => _e("Submit")));
    $html[] = "</tf>";
    $html[] = "</td></tr></table>";
    $html[] = "<table class='widefat'>";
    $html[] = "<tbody>";
    foreach($aStudentNo AS $student_no_key => $student_no_value) {
        $html[] = (0 == $student_no_key % 12)?("<thead>" . $grid->showColumn() . "</thead>"):"";
        $theStudentApply = getTheStudentApply($student_no_value);
        //var_dump($theStudentApply);
        $style = ("class='alternate'" == $style)?"":"class='alternate'";
        $html[] = "<tr $style>";
        $html[] = showSportApplyGridRow($theStudentApply);
    }
    $html[] = "</tbody>";
    $html[] = "</table>";
    return implode("", $html);
}
/**
 * getTheStudentApply()
 *
 * @param string $sStudentNo
 * @return
 */
function getTheStudentApply($sStudentNo = "")
{
    $sql = "SELECT * FROM " . DB_PREFIX . "sport_apply WHERE student_no='" . $sStudentNo . "'";
    $result = zeus_sql_query($sql, false);
    if (null != $result) {
        $apply = array('sport_apply_id' => $result['sport_apply_id'],
            'student_no' => $result['student_no'],
            'student_name' => getTheStudentName($sStudentNo),
            'sex_id' => $result['sex_id'],
            'sport_id' => $result['sport_id'],
            'projects' => $result['projects'],
            'group_id' => $result['group_id']
            );
        return $apply;
    } else {
        return false;
    }
}

/**
 * isSpillPersonEveryProject()
 *
 * @param integer $person
 * @return
 */
function isSpillPersonEveryProject($iPerson = 0)
{
    if ($iPerson > MAX_PERSON_EVERY_PROJECT) {
        return true;
    } else {
        return false;
    }
}
/**
 * isSpillProjectEveryPerson()
 *
 * @param array $project
 * @return
 */
function isSpillProjectEveryPerson($iProject = 0)
{
    if ($iProject > MAX_PROJECTS_EVERY_PERSON) {
        return true;
    } else {
        return false;
    }
}
/**
 * addSportApply()
 *
 * @param array $aApplyId
 * @param array $aSexId
 * @param array $a100M
 * @param array $a200M
 * @param array $a400M
 * @param array $a800M
 * @param array $a1000M
 * @param array $a1500M
 * @param array $aHighJump
 * @param array $aLongJump
 * @param array $aThows
 * @param array $aShot
 * @return
 */
function addSportApply($aApplyId = array(),
    $a100M = array(),
    $a200M = array(),
    $a400M = array(),
    $a800M = array(),
    $a1000M = array(),
    $a1500M = array(),
    $aHighJump = array(),
    $aLongJump = array(),
    $aThows = array(),
    $aShot = array())
{
    foreach($aApplyId AS $apply_id_key => $apply_id_value) {
        $aApply[] = array(":sport_apply_id" => $apply_id_value,
            ":projects" => getSportProjects($apply_id_value,
                $a100M,
                $a200M,
                $a400M,
                $a800M,
                $a1000M,
                $a1500M,
                $aHighJump,
                $aLongJump,
                $aThows,
                $aShot)
            );
    }
    $sql = "UPDATE " . DB_PREFIX . "sport_apply SET
	projects = :projects
	WHERE sport_apply_id = :sport_apply_id";
    zeus_sql_prepare($sql, false, $aApply);
    return true;
}
/**
 * getSportApplySexId()
 *
 * @param string $key
 * @param array $aSexId
 * @return
 */
function getSportApplySexId($key = "", $aSexId = array())
{
    foreach($aSexId AS $sex_id_key => $sex_id_value) {
        if ($key == $sex_id_key) {
            return $sex_id_value;
        } else {
            zeus_do_nothing();
        }
    }
}
/**
 * getSportProjects()
 *
 * @param string $apply_id_value
 * @param array $a100M
 * @param array $a200M
 * @param array $a400M
 * @param array $a800M
 * @param array $a1000M
 * @param array $a1500M
 * @param array $aHighJump
 * @param array $aLongJump
 * @param array $aThows
 * @param array $aShot
 * @return
 */
function getSportProjects($apply_id_value = "",
    $a100M = array(),
    $a200M = array(),
    $a400M = array(),
    $a800M = array(),
    $a1000M = array(),
    $a1500M = array(),
    $aHighJump = array(),
    $aLongJump = array(),
    $aThows = array(),
    $aShot = array()
    )
{
    // Add the project code
    if (isset($a100M) && is_array($a100M) && in_array($apply_id_value, $a100M)) {
        $projects[] = "A";
    } else {
        $projects[] = "0";
    }
    if (isset($a200M) && is_array($a200M) && in_array($apply_id_value, $a200M)) {
        $projects[] = "B";
    } else {
        $projects[] = "0";
    }
    if (isset($a400M) && is_array($a400M) && in_array($apply_id_value, $a400M)) {
        $projects[] = "C";
    } else {
        $projects[] = "0";
    }
    if (isset($a800M) && is_array($a800M) && in_array($apply_id_value, $a800M)) {
        $projects[] = "D";
    } else {
        $projects[] = "0";
    }
    if (isset($a1000M) && is_array($a1000M) && in_array($apply_id_value, $a1000M)) {
        $projects[] = "E";
    } else {
        $projects[] = "0";
    }
    if (isset($a1500M) && is_array($a1500M) && in_array($apply_id_value, $a1500M)) {
        $projects[] = "F";
    } else {
        $projects[] = "0";
    }
    if (isset($aHighJump) && is_array($aHighJump) && in_array($apply_id_value, $aHighJump)) {
        $projects[] = "G";
    } else {
        $projects[] = "0";
    }
    if (isset($aLongJump) && is_array($aLongJump) && in_array($apply_id_value, $aLongJump)) {
        $projects[] = "H";
    } else {
        $projects[] = "0";
    }
    if (isset($aThows) && is_array($aThows) && in_array($apply_id_value, $aThows)) {
        $projects[] = "I";
    } else {
        $projects[] = "0";
    }
    if (isset($aShot) && is_array($aShot) && in_array($apply_id_value, $aShot)) {
        $projects[] = "J";
    } else {
        $projects[] = "0";
    }
    // Get projects code
    if (isset($projects) && is_array($projects)) {
        return implode("", $projects);
    } else {
        return false;
    }
}
/**
 * getApplyProjectsChecked()
 *
 * @param string $sApplyId
 * @return
 */
function getApplyProjectsChecked($sApplyId = "")
{
    $sql = "SELECT projects FROM " . DB_PREFIX . "sport_apply WHERE sport_apply_id ='" . $sApplyId . "'";
    $result = zeus_sql_query($sql, false);
    if (isset($result)) {
        $projects = "";
        $projects = $result['projects'];
        $applied = str_split($projects);
        //var_dump($applied);
        if (isset($applied) && is_array($applied)) {
            $checked = array();
            foreach($applied AS $project_id) {
                $checked[] = in_array("A", $applied);
                $checked[] = in_array("B", $applied);
                $checked[] = in_array("C", $applied);
                $checked[] = in_array("D", $applied);
                $checked[] = in_array("E", $applied);
                $checked[] = in_array("F", $applied);
                $checked[] = in_array("G", $applied);
                $checked[] = in_array("H", $applied);
                $checked[] = in_array("I", $applied);
                //$checked[] = in_array("J", $applied);
                //var_dump($checked);
                return $checked;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * syncApplyList()
 *
 * @return
 */
function syncApplyList()
{
    // Get current student no
    $allStudentNo = getAllStudentNo();
    //var_dump($allStudentNo);
    $applyStudentNo = getApplyStudentNo();         
    $disableStudentNo = getDisableStudentNo();
    // Get diffient student no
    if(false == $applyStudentNo)
    {
          $diffStudentNo =  $allStudentNo;
    }
    else
    {
          $diffStudentNo = getDiffStudentNo($allStudentNo, $applyStudentNo);           
    } 
    // Add the new student no tp apply
    addNewStudentToApply($diffStudentNo);
    removeDisableStudentFromApply($disableStudentNo);
    syncApplySex();
}

function syncApplySex()
{
     $sql = "SELECT student_no,sex_id FROM ".DB_PREFIX."sport_apply";
     $aApplyInfo = zeus_sql_query($sql,false,'All');
     //var_dump($aApplyInfo);
     foreach($aApplyInfo AS $applyStudent)
     {
         $sql = "SELECT sex_id FROM ".DB_PREFIX."rel_student_info WHERE student_no='".$applyStudent['student_no']."'"; 
         $studentInfo = zeus_sql_query($sql,false);
         if($studentInfo['sex_id']!=$applyStudent['sex_id'])
         {
             $data[] = array(':student_no' => $applyStudent['student_no'],
                    ':sex_id' => $studentInfo['sex_id']
                    );
            //echo "F";
         }
         else
         {   
            //echo "T";
            zeus_do_nothing();             
         }
     }
     //var_dump($data); 
     $sql = "UPDATE ".DB_PREFIX."sport_apply SET sex_id=:sex_id WHERE student_no=:student_no";
     if (zeus_sql_prepare($sql, false, $data)) {
            return true;
        } else {
            return false;
        }                                                                              
}

/**
 * addNewStudentToApply()
 *
 * @param array $aStudentNo
 * @return
 */
function addNewStudentToApply($aStudentNo = array())
{
    $sport_id = getLatestSportId();
    if (isset($aStudentNo) && null != $aStudentNo) {
        foreach($aStudentNo AS $student_no) {
            $sql = "SELECT student_no,sex_id FROM " . DB_PREFIX . "rel_student_info WHERE student_no='" . $student_no . "'";
            $result = zeus_sql_query($sql, false);
            if (isset($result) && null != $result) {
                $data[] = array(':student_no' => $result['student_no'],
                    ':sport_id' => $sport_id ,
                    ':sex_id' => $result['sex_id']
                    );
            } else {
                zeus_do_nothing();
            }
        }
        $sql = "INSERT INTO " . DB_PREFIX . "sport_apply SET student_no=:student_no,sex_id=:sex_id,sport_id=:sport_id";
        if (zeus_sql_prepare($sql, false, $data)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * removeDisableStudentFromApply()
 *
 * @param array $aDisable
 * @return
 */
function removeDisableStudentFromApply($aDisable = array())
{
    if (isset($aDisable) && null != $aDisable) {
        foreach($aDisable AS $student_no) {
            $data[] = array(':student_no' => $student_no);
        }
        $sql = "DELETE FROM " . DB_PREFIX . "sport_apply WHERE student_no=:student_no";
        if (zeus_sql_prepare($sql, false, $data)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * getLatestSportId()
 *
 * @return
 */
function getLatestSportId()
{
    $sql = "SELECT MAX(sport_id) FROM " . DB_PREFIX . "sport";
    $result = zeus_sql_query($sql, false);
    if (isset($result) && null != $result) {
        return $result['MAX(sport_id)'];
    } else {
        return false;
    }
}

/**
 * getLatestSportName()
 *
 * @return
 */
function getLatestSportName()
{
    $lastId = getLatestSportId();
    $sql = "SELECT sport_name FROM " . DB_PREFIX . "sport WHERE sport_id='" . $lastId . "'";
    $result = zeus_sql_query($sql, false);
    if (isset($result) && null != $result) {
        return $result['sport_name'];
    } else {
        return false;
    }
}

/**
 * updateSportTeamId()
 *
 * @return
 */
function freshApplyTable()
{
    $nullCode = '0000000000'; 
    setApplyedFlag($nullCode);
    updateGroupIdInApply();
}

function setApplyedFlag($nullCode)
{
    $sql = "UPDATE ". DB_PREFIX . "sport_apply SET group_id = '0' WHERE projects = '".$nullCode."'";
    zeus_sql_exec($sql, false);
    $sql = "UPDATE ". DB_PREFIX . "sport_apply SET group_id = '1' WHERE projects != '".$nullCode."'";
    zeus_sql_exec($sql, false); 
}

function updateGroupIdInApply()
{
    $sql = "SELECT * FROM ". DB_PREFIX . "sport_apply  WHERE group_id = '1'"; 
    $aApplyedInfo = zeus_sql_query($sql, false,'All');
    //var_dump($aApplyedInfo);
    foreach($aApplyedInfo AS $applyed)
    {
        $sql = "SELECT myclass_id FROM ".DB_PREFIX."rel_student_info WHERE student_no='".$applyed['student_no']."'";
        $result = zeus_sql_query($sql,false);
        $myclass_id = unserialize($result['myclass_id']);
        $sql = "SELECT department_id FROM ".DB_PREFIX."myclass WHERE myclass_id='".$myclass_id."'";
        $result = zeus_sql_query($sql,false);         
        $departId = $result['department_id'];
        //echo $departId;
        $sexId = $applyed['sex_id'];
        $projectId = getProjectsCode((string)$applyed['projects']); 
        $groupId = $departId.$sexId.$projectId;
        $data[] = array(':student_no' => $applyed['student_no'],
                    ':group_id' => $groupId
                    );
    }
    //var_dump($data);
    $sql = "UPDATE ".DB_PREFIX."sport_apply SET group_id=:group_id WHERE student_no=:student_no";
    zeus_sql_prepare($sql, false, $data);
    /*
    if (zeus_sql_prepare($sql, false, $data)) {
            return true;
        } else {
            return false;
        } 
    */
}

/**
 * getStudentTeam()
 *
 * @return
 */
function getStudentTeam()
{
    $sportId = getLatestSportId();
    $sql = "SELECT " . DB_PREFIX . "sport_apply.student_no AS student_no,"
     . DB_PREFIX . "sport_apply.sex_id AS sex_id,"
     . DB_PREFIX . "sport_apply.projects AS projects,"
     . DB_PREFIX . "rel_student_info.myclass_id AS myclass_id"
     . " FROM "
     . DB_PREFIX . "sport_apply,"
     . DB_PREFIX . "rel_student_info"
     . " WHERE "
     . DB_PREFIX . "sport_apply.sport_id='"
     . $sportId . "' AND "
     . DB_PREFIX . "sport_apply.student_no="
     . DB_PREFIX . "rel_student_info.student_no";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $data) {
            $myclass_id = unserialize($data['myclass_id']);
            $termIndex = getTermIndex();
            $sex_id = $data['sex_id'];
            $project_code = getProjectsCode((string)$data['projects']);
            $team[] = array(':student_no' => $data['student_no'],
                ':group_id' => getTheClassDepartmentId($myclass_id)
                 . $sex_id . $project_code);
        }
        return $team;
    } else {
        return false;
    }
}
/**
 * getProjectsCode()
 *
 * @param string $sProjects
 * @return
 */
function getProjectsCode($sProjects = "")
{
    if (isset($sProjects) && null != $sProjects) {
        $rsCount = strlen($sProjects);
        for($rsIndex = 0;$rsIndex < $rsCount;$rsIndex++) {
            $project = substr($sProjects, $rsIndex, 1);
            switch ($project) {
                case "A":
                case "B":
                case "C":
                case "D":
                case "E":
                case "F":
                case "G":
                case "H":
                case "I":
                case "J":
                    $code[] = $project;
                    break;
                default:
                    $code[] = null;
                    break;
            }
        }
    } else {
        $code[] = null;
    }
    return implode("", $code);
}
/**
 * getTheClassDepartmentId()
 *
 * @param string $sClassId
 * @return
 */
function getTheClassDepartmentId($sClassId = "")
{
    $sql = "SELECT department_id FROM "
     . DB_PREFIX . "myclass WHERE myclass_id='"
     . $sClassId . "'";
    $result = zeus_sql_query($sql, false);
    if (isset($result) && null != $result) {
        return $result['department_id'];
    } else {
        return false;
    }
}

/**
 * getTeamsId()
 *
 * @param string $bEnable
 * @return
 */
function getGroupId($bEnable = "1")
{
    $sql = "SELECT group_id FROM " . DB_PREFIX . "sport_group WHERE is_enable='" . $bEnable . "'";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $data) {
            $teamId[] = $data['group_id'];
        }
        return $teamId;
    } else {
        return false;
    }
}

/**
 * getStudentNoInTeam()
 *
 * @param string $sGroupId
 * @return
 */
function getStudentNoInGroup($sGroupId = "")
{
    $which_project = substr($sGroupId, 0, 3) . "%" . substr($sGroupId, 3, 1) . "%";
    //echo  $which_project;
    $sql = "SELECT student_no FROM " . DB_PREFIX . "sport_apply WHERE group_id LIKE '" . $which_project . "'";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $data) {
            $aStudentNo[] = $data['student_no'];
        }
        return $aStudentNo;
    } else {
        return false;
    }
}

/**
 * groupStudentNoInTrack()
 *
 * @param array $aStudentNo
 * @param string $sGroupId
 * @return
 */
function groupStudentNoInTrack($aStudentNo = array(), $sGroupId = "")
{
    $groupInfo = array();
    $count = 0;
    // Check student number first!!!
    // echo (count($aStudentNo)." ");
    if (isset($aStudentNo) && isset($sGroupId) && null != $aStudentNo && null != $sGroupId) {
        for($roadIndex = 0;$roadIndex < MAX_TRACK_ROAD;$roadIndex++) {
            if (count($aStudentNo) > (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM-1) && count($aStudentNo) <= (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM)) {
                for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            } elseif (count($aStudentNo) <= (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM-1) && count($aStudentNo) > (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM-2)) {
                for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM-1;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            } elseif (count($aStudentNo) <= (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM-2) && count($aStudentNo) > 0) {
                for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM-2;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            } else {
                // echo $sGroupId;
                $aStudentNo = array_slice($aStudentNo, 0, (MAX_TRACK_ROAD) * (MAX_TRACK_TEAM));
                for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            }
        }

        return shuffleStudentNoInGroup($groupInfo);
    } else {
    }
}
/**
 * shuffleStudentNoInGroup()
 *
 * @param array $aGroupInfo
 * @return
 */
function shuffleStudentNoInGroup($aGroupInfo = array())
{
    if (isset($aGroupInfo) && null != $aGroupInfo) {
        for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
            for($roadIndex = 0;$roadIndex < MAX_TRACK_ROAD;$roadIndex++) {
                $switch[$teamIndex][$roadIndex] = $aGroupInfo[$roadIndex][$teamIndex];
            }
        }
        // var_dump($switch);
        for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
            shuffle($switch[$teamIndex]);
        }
        // sort road
        asort($switch);
        for($roadIndex = 0;$roadIndex < MAX_TRACK_ROAD;$roadIndex++) {
            for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
                $aGroupInfo[$roadIndex][$teamIndex] = $switch[$teamIndex][$roadIndex];
            }
        }
        return $aGroupInfo;
    } else {
        return false;
    }
}

/**
 * groupStudentNoInField()
 *
 * @param array $aStudentNo
 * @param string $sGroupId
 * @return
 */
function groupStudentNoInField($aStudentNo = array(), $sGroupId = "")
{
    $groupInfo = array();
    $count = 0;
    // Check student number first!!!
    // echo (count($aStudentNo) . " ");
    if (isset($aStudentNo) && isset($sGroupId) && null != $aStudentNo && null != $sGroupId) {
        shuffle($aStudentNo);
        for($roadIndex = 0;$roadIndex < MAX_FIELD_ROAD;$roadIndex++) {
            if (count($aStudentNo) <= MAX_FIELD_ROAD) {
                for($teamIndex = 0;$teamIndex < MAX_FIELD_TEAM;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            } else {
                //echo $sGroupId;
                $aStudentNo = array_slice($aStudentNo, 0, (MAX_FIELD_ROAD) * (MAX_FIELD_TEAM));
                for($teamIndex = 0;$teamIndex < MAX_FIELD_TEAM;$teamIndex++) {
                    $groupInfo[$roadIndex][$teamIndex] = $aStudentNo[$count];
                    $count++;
                }
            }
        }
        return $groupInfo;
    } else {
    }
}
/**
 * updateGroup()
 *
 * @param array $aGroupInfo
 * @param string $sGroupId
 * @return
 */
function updateTrack($aGroupInfo = array(), $sGroupId = "")
{
    $sport_id = getLatestSportId();
    if (isset($aGroupInfo) && null != $aGroupInfo) {
        for($roadIndex = 0;$roadIndex < MAX_TRACK_ROAD;$roadIndex++) {
            for($teamIndex = 0;$teamIndex < MAX_TRACK_TEAM;$teamIndex++) {
                $student_no = $aGroupInfo[$roadIndex][$teamIndex];
                if (null != $student_no) {
                    $group[] = array(':student_no' => $student_no,
                        ':road_id' => $roadIndex + 1,
                        ':subteam_id' => $teamIndex + 1,
                        ':sport_id' => $sport_id,
                        ':group_id' => $sGroupId
                        );
                } else {
                    zeus_do_nothing();
                }
            }
        }
        $sql = "REPLACE INTO " . DB_PREFIX . "sport_arrangement SET road_id=:road_id,subteam_id=:subteam_id,student_no=:student_no,sport_id=:sport_id,group_id=:group_id";
        if (zeus_sql_prepare($sql, false, $group)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function updateField($aGroupInfo = array(), $sGroupId = "")
{
    $sport_id = getLatestSportId();
    if (isset($aGroupInfo) && null != $aGroupInfo) {
        for($roadIndex = 0;$roadIndex < MAX_FIELD_ROAD;$roadIndex++) {
            for($teamIndex = 0;$teamIndex < MAX_FIELD_TEAM;$teamIndex++) {
                $student_no = $aGroupInfo[$roadIndex][$teamIndex];
                if (null != $student_no) {
                    $group[] = array(':student_no' => $student_no,
                        ':road_id' => $roadIndex + 1,
                        ':subteam_id' => $teamIndex + 1,
                        ':sport_id' => $sport_id,
                        ':group_id' => $sGroupId
                        );
                } else {
                    zeus_do_nothing();
                }
            }
        }
        $sql = "REPLACE INTO " . DB_PREFIX . "sport_arrangement SET road_id=:road_id,subteam_id=:subteam_id,student_no=:student_no,sport_id=:sport_id,group_id=:group_id";
        if (zeus_sql_prepare($sql, false, $group)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * groupSport()
 *
 * @return
 */
function groupTrack()
{
    $aGroupId = getGroupId();
    //var_dump($aGroupId);
    $sport_id = getLatestSportId();
    removeTrack();
    if (isset($aGroupId) && null != $aGroupId) {
        foreach($aGroupId AS $group_id) {
            $trackName = substr($group_id, 3, 1);
            switch ($trackName) {
                case "A":
                case "B":
                case "C":
                    $aStudentNo = getStudentNoInGroup($group_id);
                    //var_dump($aStudentNo);
                    $aGroupInfo = groupStudentNoInTrack($aStudentNo, $group_id);
                    updateTrack($aGroupInfo, $group_id);
                    break;
                default:
                    zeus_do_nothing();
                    break;
            }
        }
    } else {
        return false;
    }
}
/**
 * groupField()
 *
 * @return
 */
function groupField()
{
    $aGroupId = getGroupId();
    $sport_id = getLatestSportId();
    removeField();
    // var_dump($aTeam);
    if (isset($aGroupId) && null != $aGroupId) {
        foreach($aGroupId AS $group_id) {
            $track = substr($group_id, 3, 1);
            switch ($track) {
                case "D":
                case "E":
                case "F":
                case "G":
                case "H":
                case "I":
                case "J":
                    $aStudentNo = getStudentNoInGroup($group_id);
                    // var_dump($aStudentNo);
                    $aGroupInfo = groupStudentNoInField($aStudentNo, $group_id);
                    // var_dump($aGroupInfo);
                    updateField($aGroupInfo, $group_id);
                    break;
                default:
                    zeus_do_nothing();
                    break;
            }
        }
    } else {
        return false;
    }
}
/**
 * removeTrack()
 *
 * @return
 */
function removeTrack()
{
    $sport_id = getLatestSportId();
    $sql = "SELECT arrange_id FROM " . DB_PREFIX . "sport_arrangement";
    if (null != zeus_sql_query($sql, false, 'All')) {
        $sql = "DELETE FROM " . DB_PREFIX . "sport_arrangement WHERE (sport_id='" . $sport_id . "' AND group_id LIKE '%A')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%B')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%C')";
        if (0 != zeus_sql_exec($sql, false)) {
            return true;
        } else {
            return false;
        }
    } else {
        zeus_do_nothing();
        return false;
    }
}

/**
 * removeField()
 *
 * @return
 */
function removeField()
{
    $sport_id = getLatestSportId();
    $sql = "SELECT arrange_id FROM " . DB_PREFIX . "sport_arrangement";
    if (null != zeus_sql_query($sql, false, 'All')) {
        $sql = "DELETE FROM " . DB_PREFIX . "sport_arrangement WHERE (sport_id='" . $sport_id . "' AND group_id LIKE '%D')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%E')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%F')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%G')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%H')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%I')"
         . " OR (sport_id='" . $sport_id . "' AND group_id LIKE '%J')";
        if (0 != zeus_sql_exec($sql, false)) {
            return true;
        } else {
            return false;
        }
    } else {
        zeus_do_nothing();
        return false;
    }
}

/**
 * getTrackGroup()
 *
 * @param string $bEnable
 * @return
 */
function getTrackGroup($bEnable = "1")
{
    $sql = "SELECT group_id,group_name FROM " . DB_PREFIX . "sport_group WHERE (is_enable='" . $bEnable . "' AND group_id LIKE '%A')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%B')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%C')" ;
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $data) {
            $key[] = $data['group_id'];
            $value[] = $data['group_name'];
        }
        $track = array_combine($key, $value);
        return $track;
    } else {
        return false;
    }
}
/**
 * getFieldGroup()
 *
 * @param string $bEnable
 * @return
 */
function getFieldGroup($bEnable = "1")
{
    $sql = "SELECT group_id,group_name FROM " . DB_PREFIX . "sport_group WHERE (is_enable='" . $bEnable . "' AND group_id LIKE '%D')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%E')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%F')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%G')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%H')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%I')"
     . " OR (is_enable='" . $bEnable . "' AND group_id LIKE '%J')" ;
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $data) {
            $key[] = $data['group_id'];
            $value[] = $data['group_name'];
        }
        $field = array_combine($key, $value);
        return $field;
    } else {
        return false;
    }
}

?>